package com.jiaai.web.zfp_back.system;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jiaai.system.api.ISystemConfigApi;
import com.jiaai.util.RestResultGenerator;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

/**
 * class_name:ZBCertController
 * describe:------------------>证书上传
 * create_user:张昉平
 * create_date:2018/1/20
 * create_time:16:05
 */
@RestController
@RequestMapping("/api/v1/cert")
public class ZBCertController {

    @Reference
    private ISystemConfigApi systemConfigApi;

    /**
     * 上传证书的
     * @param request
     * @return
     * @throws FileNotFoundException
     */
    @PostMapping("/upload")
    public Object upload(HttpServletRequest request) throws FileNotFoundException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        String fileName = null;
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                String key=iter.next();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(key);
                fileName = file.getOriginalFilename();
                byte[] b = null;
                try {
                    b = file.getBytes();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // String url=URLEncoder.encode(UploadUtil.getHttpUrl(fileName,directories),"utf-8");
                String s = org.apache.commons.codec.binary.Base64.encodeBase64String(b);
                if (systemConfigApi.certIntoRedis(fileName, s)){
                    return RestResultGenerator.genSuccessResult(fileName);
                }else {
                    return RestResultGenerator.genErrorResult("失败");
                }
            }

        }
        return RestResultGenerator.genErrorResult("失败");
    }
}
